import ala from '@/service/ala'
const allKeys = 'localStorage_allKeys'
import store from '@/store'

//  存储localStorage
export function localSet(name, data, encrypt = false) {
  if (!data || !name) {
    return
  }
  name = getKey(name)
  data = JSON.stringify(data)
  if (encrypt === false) {
    window.localStorage.setItem(name, data)
  } else {
    var encryptData = ala.encrypt(data, name)
    window.localStorage.setItem(name, encryptData)
  }
  setKeys(name)
}
//  获取localStorage
export function localGet(name, encrypt = false) {
  if (!name) return
  name = getKey(name)
  var data = window.localStorage.getItem(name)
  if (data && data !== 'undefined') {
    if (encrypt === true) {
      try {
        var decryptStr = ala.decrypt(data, name)
      } catch {
        console.error('加密解析出错,自动清空缓存')
        localClear(true)
        ala.userLogout('/admin/index', false)
      }
      var decryptData = JSON.parse(decryptStr)
      return decryptData
    } else {
      try {
        var value = JSON.parse(data)
        return value
      } catch {

      }
    }
  }
}

// 保存所有的Keys
function setKeys(name) {
  var keys = localGet(allKeys)
  if (!keys) {
    keys = []
  }
  if (keys.indexOf(name) < 0) {
    keys.push(name)
    localSet(allKeys, keys)
  }
}
//  删除localStorage
export function localRemove(name) {
  if (!name) return
  name = getKey(name)
  window.localStorage.removeItem(name)
  store.state[name] = null
}

// 本地缓存所有键

export function localClear(clearAll = false, signFool = false) {
  var keys = localGet(allKeys)
  if (keys !== undefined && keys !== null) {
    keys.forEach(element => {
      if (clearAll) {
        localRemove(element)
      } else {
        if (!(element === 'alapc__tenant' || element.toLowerCase().indexOf('alapc__user_') === 0)) {
          if (!signFool) {
            localRemove(element) // 租户标识不能删除
          } else {
            if (!(element === 'alapc__tenant' || element.toLowerCase().indexOf('alapc__user_') === 0 || element.toLowerCase().indexOf('alapc__security_') === 0)) {
              localRemove(element) // sing后台安全码
            }
          }
        }
      }
    })
  }
  localRemove(allKeys)
}

function getKey(name) {
  if (name.indexOf('alapc__') === 0) {
    return name
  }
  return 'alapc__' + name
}
